<!-- 适用于小程序特殊的透明登录按钮 -->

<script lang="ts" setup>
import { userApi } from '@/request/api'
import { useDict, useProfile } from '@/stores'
import { DictCode } from '@/types/api/public'
import {
  useConsole,
  useHideLoading,
  useJsonDeepParse,
  useLoading,
  useToast,
} from '@/utils'
import { to } from 'await-to-js'
import { pick } from 'lodash-es'

const emit = defineEmits(['done'])
const profile = useProfile()
const dict = useDict()
// 支付宝小程序登录
// #ifdef MP-ALIPAY
async function onGetAuthorize(e: any) {
  useConsole?.log(1, 'onGetAuthorize:success', e)
  useLoading(true)

  my.getAuthCode({
    fail: (getAuthCodeErr: any) => {
      useConsole?.log(2, 'getAuthCode:fail', getAuthCodeErr)
      useHideLoading()
    },
    success: (getAuthCodeRes: any) => {
      useConsole?.log(2, 'getAuthCode:success', getAuthCodeRes)

      my.getOpenUserInfo({
        fail: (getOpenUserInfoErr: any) => {
          useConsole?.log(3, 'getOpenUserInfo:fail', getOpenUserInfoErr)
          useHideLoading()
        },
        success: async (getOpenUserInfoRes: any) => {
          useConsole?.log(3, 'getOpenUserInfo:success', getOpenUserInfoRes)

          try {
            const body = {
              appletId: my.getAppIdSync().appId,
              devInfo: JSON.stringify(uni.getSystemInfoSync()),
              promotionAccount: profile.userRelationship?.promotionAccount,
              flowState: profile.userRelationship?.flowState,
              code: getAuthCodeRes.authCode,
              authCode: getAuthCodeRes.authCode,
              param: getOpenUserInfoRes.response,
            }
            const [err, res] = await to(userApi.login(body))
            useHideLoading()
            if (err) {
              return
            }

            uni.setStorageSync('token', res.token)
            uni.setStorageSync(
              'userInfo',
              useJsonDeepParse(JSON.stringify(res.user)),
            )
            dict.init({ dictCode: DictCode.rentType })
            profile.init()
            emit('done')
          }
          catch (error) {
            useConsole?.error('getOpenUserInfo:success:login', error)
          }
        },
      })
    },
  })
}

async function onGetAuthorizeError(err: any) {
  useConsole?.log('onGetAuthorize:fail', err)
}
// #endif

// 微信小程序登录
// #ifdef MP-WEIXIN
async function handleWXLogin() {
  useLoading(true)
  wx.login({
    fail: (loginErr: any) => {
      useConsole?.log(1, 'login:fail', loginErr)
      useHideLoading()
    },
    success: async (loginRes: any) => {
      useConsole?.log(1, 'login:success', loginRes)

      wx.getUserInfo({
        fail: (getUserInfoErr: any) => {
          useConsole?.log(2, 'getUserInfoErr:fail', getUserInfoErr)
          useHideLoading()
        },
        success: async (getUserInfoRes: any) => {
          useConsole?.log(2, 'getUserInfoRes:success', getUserInfoRes)

          try {
            const body = {
              appletId: wx.getAccountInfoSync().miniProgram.appId,
              devInfo: JSON.stringify(uni.getSystemInfoSync()),

              promotionAccount: profile.userRelationship?.promotionAccount,
              flowState: profile.userRelationship?.flowState,

              code: loginRes.code,
              ...pick(getUserInfoRes, [
                'encryptedData',
                'iv',
                'signature',
                'userInfo',
                'rawData',
              ]),
              // ...getUserInfoRes,
            }
            const [err, res] = await to(userApi.login(body))
            useHideLoading()
            if (err) {
              return
            }
            uni.setStorageSync('token', res.token)
            uni.setStorageSync(
              'userInfo',
              useJsonDeepParse(JSON.stringify(res.user)),
            )
            dict.init({ dictCode: DictCode.rentType })
            profile.init()
            emit('done')
          }
          catch (error) {
            useConsole?.error('getOpenUserInfo:success:login', error)
          }
        },
      })
    },
  })
}
// #endif

// 快手登录
// #ifdef MP-KUAISHOU
async function onKuaishou() {
  useLoading(true)
  ks.login({
    fail(loginErr: any) {
      useHideLoading()
    },
    success(loginRes: any) {
      ks.authorize({
        scope: 'scope.userInfo',
        async  fail() {
          useToast('拒绝授权')
          useHideLoading()
          const { authSetting } = await ks.getSetting()
          if (authSetting['scope.userInfo']) {
            console.log('已授权用户信息')
          }
          else {
            const { authSetting } = await ks.openSetting()
            console.log('已授权用户信息', authSetting)
          }
        },
        async success() {
          ks.getUserInfo({
            async success(getUserInfoRes: any) {
              const body = {
                appletId: uni.getAccountInfoSync().miniProgram.appId,
                devInfo: JSON.stringify(uni.getSystemInfoSync()),
                promotionAccount: profile.userRelationship?.promotionAccount,
                flowState: profile.userRelationship?.flowState,
                code: loginRes.code,
                param: JSON.stringify(getUserInfoRes.userInfo),
              }
              const [err, res] = await to(userApi.login(body))
              useHideLoading()
              if (err) {
                return
              }
              uni.setStorageSync('token', res.token)
              uni.setStorageSync(
                'userInfo',
                useJsonDeepParse(JSON.stringify(res.user)),
              )

              profile.init()
              dict.init({ dictCode: DictCode.rentType })
              emit('done')
            },
            fail(getUserInfoErr: any) {
              console.log('getUserInfo:fail', getUserInfoErr)
              useHideLoading()
            },
          })
        },
      })
    },
  })
}

// #endif
</script>

<template>
  <!-- #ifdef MP-WEIXIN -->
  <button
    class="absolute top-0 h-full w-full op-0"
    @click="handleWXLogin"
  ></button>
  <!-- #endif -->
  <!-- #ifdef MP-ALIPAY -->
  <button
    class="absolute top-0 h-full w-full op-0"
    open-type="getAuthorize"
    scope="userInfo"
    @getAuthorize="onGetAuthorize"
    @error="onGetAuthorizeError"
  ></button>
  <!-- #endif -->
  <!-- #ifdef MP-KUAISHOU -->
  <button
    class="absolute top-0 h-full w-full op-0"
    open-type="getUserInfo"
    @getuserinfo="onKuaishou"
  ></button>
  <!-- #endif -->
</template>

<style lang="less" scoped></style>
